// 完全符合多标签多角色隔离的 UserIdentityManager，currentRole 只走 sessionStorage
// 并且全局唯一登录主键统一为 loginId，不再使用 userId
class UserIdentityManager {
  static setUserIdentity(role, userData) {
    const timestamp = Date.now();
    const sessionId = this.generateSessionId();
    switch(role) {
      case 'admin':
        localStorage.setItem('admin_loginId', userData.id); // login表主键
        localStorage.setItem('admin_username', userData.username || userData.name);
        localStorage.setItem('admin_role', 'admin');
        localStorage.setItem('admin_token', userData.token || '');
        localStorage.setItem('admin_loginTime', timestamp);
        localStorage.setItem('admin_sessionId', sessionId);
        localStorage.setItem('admin_name', userData.name || userData.username || '');
        break;
      case 'travel':
        localStorage.setItem('travel_loginId', userData.id);
        localStorage.setItem('travel_username', userData.username || userData.name);
        localStorage.setItem('travel_role', 'travel');
        localStorage.setItem('travel_token', userData.token || '');
        localStorage.setItem('travel_loginTime', timestamp);
        localStorage.setItem('travel_sessionId', sessionId);
        localStorage.setItem('travel_name', userData.name || userData.username || '');
        break;
      case 'user':
      default:
        localStorage.setItem('user_loginId', userData.id);
        localStorage.setItem('user_username', userData.username || userData.name);
        localStorage.setItem('user_role', 'user');
        localStorage.setItem('user_token', userData.token || '');
        localStorage.setItem('user_loginTime', timestamp);
        localStorage.setItem('user_sessionId', sessionId);
        localStorage.setItem('userAccount', userData.username || userData.name);
        localStorage.setItem('user_name', userData.name || userData.username || '');
        break;
    }
    // 关键：全局唯一loginId
    localStorage.setItem('loginId', userData.id);
    localStorage.setItem('userRole', role);
    localStorage.setItem('role', role);
    localStorage.setItem('isLoggedIn', 'true');
    localStorage.setItem('username', userData.username || userData.name);
    localStorage.setItem('name', userData.name || userData.username || '');
    sessionStorage.setItem('currentRole', role); // 当前tab激活角色只存 sessionStorage
    console.log(`用户身份设置完成: ${role} - ${userData.username || userData.name}`);
  }

  static getCurrentRole() {
    return sessionStorage.getItem('currentRole');
  }

  static getCurrentUserIdentity() {
    const currentRole = this.getCurrentRole();
    if (!currentRole) return null;
    return this.getUserByRole(currentRole);
  }

  static getUserByRole(role) {
    const prefix = this.getRolePrefix(role);
    if (!prefix) return null;
    const loginId = localStorage.getItem(`${prefix}loginId`);
    if (!loginId) return null;
    return {
      id: loginId,
      username: localStorage.getItem(`${prefix}username`),
      role: localStorage.getItem(`${prefix}role`),
      token: localStorage.getItem(`${prefix}token`),
      loginTime: localStorage.getItem(`${prefix}loginTime`),
      sessionId: localStorage.getItem(`${prefix}sessionId`)
    };
  }

  static getRolePrefix(role) {
    const prefixMap = {
      'user': 'user_',
      'admin': 'admin_',
      'travel': 'travel_'
    };
    return prefixMap[role] || '';
  }

  static switchRole(targetRole) {
    const userData = this.getUserByRole(targetRole);
    if (userData) {
      sessionStorage.setItem('currentRole', targetRole);
      localStorage.setItem('loginId', userData.id);
      localStorage.setItem('userRole', targetRole);
      localStorage.setItem('role', targetRole);
      console.log(`角色切换成功: ${targetRole}`);
      return true;
    }
    console.warn(`角色切换失败: ${targetRole} 未找到登录信息`);
    return false;
  }

  static isLoggedIn(role = null) {
    if (role) {
      return !!this.getUserByRole(role);
    }
    return localStorage.getItem('isLoggedIn') === 'true';
  }

  static getLoggedInRoles() {
    const roles = [];
    ['user', 'admin', 'travel'].forEach(role => {
      if (this.getUserByRole(role)) {
        roles.push(role);
      }
    });
    return roles;
  }

  static clearOtherRoles(currentRole) {
    const roles = ['user', 'admin', 'travel'];
    roles.forEach(role => {
      if (role !== currentRole) {
        this.clearRoleData(role);
      }
    });
  }

  static clearRoleData(role) {
    const prefix = this.getRolePrefix(role);
    if (prefix) {
      localStorage.removeItem(`${prefix}loginId`);
      localStorage.removeItem(`${prefix}username`);
      localStorage.removeItem(`${prefix}role`);
      localStorage.removeItem(`${prefix}token`);
      localStorage.removeItem(`${prefix}loginTime`);
      localStorage.removeItem(`${prefix}sessionId`);
    }
  }

  static logout(role = null) {
    const targetRole = role || this.getCurrentRole();
    if (targetRole) {
      this.clearRoleData(targetRole);
      console.log(`${targetRole} 角色已登出`);
    }
    // 如果登出的是当前角色，需要清除通用字段
    const currentRole = this.getCurrentRole();
    if (!role || role === currentRole) {
      localStorage.removeItem('loginId');
      localStorage.removeItem('userRole');
      localStorage.removeItem('role');
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('userAccount');
      sessionStorage.removeItem('currentRole');
      // 检查是否还有其他已登录的角色，如果有则切换到第一个
      const remainingRoles = this.getLoggedInRoles();
      if (remainingRoles.length > 0) {
        this.switchRole(remainingRoles[0]);
      }
    }
  }

  static logoutAll() {
    ['user', 'admin', 'travel'].forEach(role => {
      this.clearRoleData(role);
    });
    localStorage.removeItem('loginId');
    localStorage.removeItem('userRole');
    localStorage.removeItem('role');
    localStorage.removeItem('isLoggedIn');
    localStorage.removeItem('userAccount');
    sessionStorage.removeItem('currentRole');
    console.log('所有角色已登出');
  }

  static generateSessionId() {
    return 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
  }

  static getUserToken(role = null) {
    const targetRole = role || this.getCurrentRole();
    const userData = this.getUserByRole(targetRole);
    return userData ? userData.token : null;
  }

  static updateUserToken(token, role = null) {
    const targetRole = role || this.getCurrentRole();
    const prefix = this.getRolePrefix(targetRole);
    if (prefix) {
      localStorage.setItem(`${prefix}token`, token);
    }
  }

  static isSessionExpired(maxAge = 24 * 60 * 60 * 1000, role = null) {
    const userData = this.getUserByRole(role || this.getCurrentRole());
    if (!userData || !userData.loginTime) return true;
    const loginTime = parseInt(userData.loginTime);
    const now = Date.now();
    return (now - loginTime) > maxAge;
  }

  static debugPrintAllUsers() {
    console.group('=== 用户身份调试信息 ===');
    const currentRole = this.getCurrentRole();
    console.log('当前活跃角色:', currentRole);
    ['user', 'admin', 'travel'].forEach(role => {
      const userData = this.getUserByRole(role);
      if (userData) {
        console.log(`${role.toUpperCase()} 角色:`, userData);
      } else {
        console.log(`${role.toUpperCase()} 角色: 未登录`);
      }
    });
    console.log('已登录角色:', this.getLoggedInRoles());
    console.groupEnd();
  }
}

export default UserIdentityManager;
if (typeof window !== 'undefined') {
  window.UserIdentityManager = UserIdentityManager;
}